package org.itboys.ace.web;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.itboys.admin.entity.AdminUser;
import org.itboys.admin.entity.SysEmailTemplate;
import org.itboys.admin.service.AdminUserService;
import org.itboys.admin.service.SysEmailTemplateService;
import org.itboys.admin.tools.AdminPermissionCheck;
import org.itboys.admin.tools.AdminSessionHolder;
import org.itboys.commons.CommonConstants;
import org.itboys.commons.utils.ajax.AjaxUtils;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.mongodb.utils.page.AceJsonPageUtils;
import org.itboys.mongodb.utils.page.Page;
import org.itboys.mongodb.utils.query.AceUtils;
import org.itboys.mongodb.utils.query.QueryParamUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

/**
 * 邮件模板
 * 
 * @author huanglei
 *
 */
@RestController
@RequestMapping("/ace/sys/emailTemplate")
public class AceSysEmailTemplateController extends BaseController{
	
	@Autowired
	private SysEmailTemplateService sysEmailTemplateService;
	@Autowired
	private AdminUserService adminUserService;
	
	@RequestMapping("/list")
	public ModelAndView emailTemplateList(HttpServletRequest request, HttpServletResponse response, Model model) {
		return new ModelAndView("/ace/sys/emailTemplate-list");
	}
	
	/**
	 * 分页查询列表
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping("/emailTemplateList")
	@AdminPermissionCheck("sysEmailTemplate:list")
	public void list(HttpServletRequest request, HttpServletResponse response,Model model) {
		Map<String, Object> param = QueryParamUtils.builderQueryMap(request);
		if (null != param.get("title")) {
			param.put("title", AceUtils.getPattern(param.get("title")));
		}
		if (null != param.get("type")) {
			param.put("type", AceUtils.getPattern(param.get("type")));
		}
		Page<SysEmailTemplate> page = sysEmailTemplateService.pageQuery(param, request);
		AceJsonPageUtils.renderJsonPage(page.getTotal(), page.getData(), response);
	}
	
	/**
	 * 保存
	 * @param SysEmailTemplate
	 * @param request
	 * @param response
	 */
	@RequestMapping("/saveEmailTemplate")
	public void add(@ModelAttribute SysEmailTemplate sysEmailTemplate,HttpServletRequest request,HttpServletResponse response) {
		try{
			if(sysEmailTemplate==null||sysEmailTemplate.getId()==0l){
				sysEmailTemplateService.insert(sysEmailTemplate);
			}else{
				sysEmailTemplateService.update(sysEmailTemplate);
			}
			AjaxUtils.renderText(response, CommonConstants.SUCCESS);
		}catch(Exception e){
			logger.error("SysEmailTemplate save error", e);
			e.printStackTrace();
			AjaxUtils.renderText(response, CommonConstants.FAIL);
		}
	}
	
	/**
	 * 删除
	 * @param id
	 * @param response
	 */
	@RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
	public void delete(@PathVariable("id") Long id, HttpServletResponse response){
		try {
			sysEmailTemplateService.deleteEmailTemplate(id);
			AjaxUtils.renderText(response, CommonConstants.SUCCESS);
		} catch (Exception e) {
			logger.error("SysEmailTemplate delete error", e);
			AjaxUtils.renderText(response, CommonConstants.FAIL);
		}
	}
	
	/***
	 * 根据id查询邮件模版信息
	 * 
	 * @param id
	 * @param response
	 */
	@RequestMapping("/getEmailTemplateById/{id}")
	public void getEmailTemplateById(@PathVariable("id") Long id, HttpServletResponse response) {
		AjaxUtils.renderJson(response, sysEmailTemplateService.getById(id));
	}
	
	/**
	 * 发送邮件模版
	 */
	@RequestMapping("/sendMailTemplate/{id}")
	public void SendMailTemplate(@PathVariable("id") Long id,HttpServletResponse response){
		try{
			Map<String,String> mailParam = new HashMap<String,String>(); 
			AdminUser user = adminUserService.getById(AdminSessionHolder.getAdminUserId());
			mailParam.put("userName", user.getUsername());
			SysEmailTemplate email = sysEmailTemplateService.getById(id);
			if(email != null){
				String template = email.getEmailContent();
				String patternString = "\\$\\{(" + StringUtils.join(mailParam.keySet(), "|") + ")\\}"; 
				Pattern pattern = Pattern.compile(patternString); 
				Matcher matcher = pattern.matcher(template); 
				StringBuffer sb = new StringBuffer(); 
			    while(matcher.find()) { 
			        matcher.appendReplacement(sb, mailParam.get(matcher.group(1))); 
			    } 
			    matcher.appendTail(sb); 
			    System.out.println("发送邮件："+sb.toString());
			}
		    AjaxUtils.renderText(response, CommonConstants.SUCCESS);
		}catch(Exception e){
			e.printStackTrace();
			 AjaxUtils.renderText(response, CommonConstants.FAIL);
		}
		
	}
}
